package com.lly.songhigh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.adapter.MVDetialsListViewAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.MVDetials;
import com.lly.songhigh.entity.MVDetialsHead;
import com.lly.songhigh.mediaplayer.MyMediaPlayer;
import com.lly.songhigh.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.util.List;

/**
 * Created by 李海龙 on 15/10/28.
 */
public class SearchMVDetialsActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, AdapterView.OnItemClickListener {

    private ListView mvDetialsListview;
    private int mvUrlId, newMVUrlId;
    private String url, newUrl, descUrl, newDescUrl, mvPlayUrl, newMVPlayUrl;
    private MVDetialsHead.DataEntity dataEntity, newDataEntity;

    private List<MVDetials.DataEntity> datas, newDatas;
    private VolleySingleton volleySingleton;

    private TextView mvDetials_songName, mvDetials_singerName, mvDetialsPlayCount, mvDetialsCommentCount, mvDetialsDesc;
    private TextView MVShare;
    private View view;

    private CheckBox mv_playOrPause;
    private SeekBar mv_detials_seekBar;
    private MyMediaPlayer myMediaPlayer;
    private RelativeLayout mv_rl_control;
    private Handler handler;
    private TextView mv_currentTime, mv_maxTime;
    private boolean isPlaying = false;
    private ImageView mv_detials_back;


    private MVDetialsListViewAdapter mvDetialsListViewAdapter;
    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private String shareUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_mv_detials);
        BaseApplication.getInstance().addActivity(this);
        initView();
        initData();
        initDescData();
        initShare();
        QQShare();
    }


    private void initView() {
        view = LayoutInflater.from(this).inflate(R.layout.mv_detials_listview_head, null);

        MVShare = (TextView) view.findViewById(R.id.mv_detials_share);
        MVShare.setOnClickListener(this);
        mvDetialsListview = (ListView) findViewById(R.id.mv_detials_listView);
        mvDetialsListview.setOnItemClickListener(this);
        mvDetialsListview.addHeaderView(view);
        mvDetials_songName = (TextView) view.findViewById(R.id.mv_detials_songName);
        mvDetials_singerName = (TextView) view.findViewById(R.id.mv_detials_singerName);
        mvDetialsCommentCount = (TextView) view.findViewById(R.id.mv_detials_commentCountTv);
        mvDetialsDesc = (TextView) view.findViewById(R.id.mv_detials_discription);
        mvDetialsPlayCount = (TextView) view.findViewById(R.id.mv_detials_playCountTv);

        /*
        * MV播放
        */
        mv_playOrPause = (CheckBox) findViewById(R.id.mv_playOrPause);
        mv_playOrPause.setOnClickListener(this);
        mv_playOrPause.setOnCheckedChangeListener(this);
        mv_detials_seekBar = (SeekBar) findViewById(R.id.mv_detials_seekBar);
        mv_rl_control = (RelativeLayout) findViewById(R.id.mv_rl_control);
//      mv_rl_control.setOnClickListener(this);
        mv_currentTime = (TextView) findViewById(R.id.mv_currentTime);
        mv_maxTime = (TextView) findViewById(R.id.mv_maxTime);
        myMediaPlayer = (MyMediaPlayer) findViewById(R.id.my_mv_mediaPlayer);
        myMediaPlayer.setOnClickListener(this);
        mv_detials_back = (ImageView) findViewById(R.id.mv_detials_back);
        mv_detials_back.setOnClickListener(this);
        mvDetialsListview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        volleySingleton = VolleySingleton.getInstance();
        Intent intent = getIntent();
        mvUrlId = intent.getIntExtra("_id", 0);
        shareUrl = "http://mv.dongting.com/mv/index2.html?id=" + mvUrlId;
        url = URL.MV_DETIALS_STARTURL + mvUrlId + URL.MV_DETIALS_ENDURL;
        descUrl = URL.MV_DETAILS_HEAD_START + mvUrlId + URL.MV_DETAILS_HEAD_end;

    }

    private void initData() {
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Gson gson = new Gson();
                MVDetials mvDetials = gson.fromJson(response, MVDetials.class);
                datas = mvDetials.getData();

                mvDetialsListViewAdapter = new MVDetialsListViewAdapter(SearchMVDetialsActivity.this, datas);
                mvDetialsListview.setAdapter(mvDetialsListViewAdapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    private void initDescData() {
        StringRequest request = new StringRequest(descUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                MVDetialsHead mvDetialsHead = gson.fromJson(response, MVDetialsHead.class);
                dataEntity = mvDetialsHead.getData();
                mvDetials_singerName.setText(dataEntity.getSingerName());
                mvDetials_songName.setText(dataEntity.getVideoName());
                mvDetialsPlayCount.setText(dataEntity.getPickCount() + "");
                mvDetialsCommentCount.setText(dataEntity.getBulletCount() + "");
                if (!dataEntity.getDesc().isEmpty()) {
                    mvDetialsDesc.setText(dataEntity.getDesc());
                } else {
                    mvDetialsDesc.setVisibility(View.GONE);
                }
                mvPlayUrl = dataEntity.getMvList().get(0).getUrl();
                mv_maxTime.setText(toTime(dataEntity.getMvList().get(0).getDuration()));
                initMVPlay();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }
    private void initMVPlay() {
        myMediaPlayer.setUrl(mvPlayUrl);
        mv_detials_seekBar.setMax(myMediaPlayer.getMax());
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {

                switch (msg.what) {
                    case 1:
                        mv_detials_seekBar.setProgress(msg.arg1);
                        mv_currentTime.setText(toTime(msg.arg1));
                        break;
                    case 2:
                        mv_rl_control.setVisibility(View.GONE);
                        break;
                }
                return false;
            }
        });
        myMediaPlayer.setHandler(handler);
    }

    //MV播放、暂停
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isPlaying == false) {
            myMediaPlayer.play();
            //点击播放后3秒
            handler.sendEmptyMessageDelayed(2, 3000);
            isPlaying = true;
        } else {
            myMediaPlayer.pause();
            isPlaying = false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_mv_mediaPlayer:
                //点击控制界面出现
                mv_rl_control.setVisibility(View.VISIBLE);
                //处理消息队列里其等于2的消息
                handler.removeMessages(2);
                handler.sendEmptyMessageDelayed(2, 3000);
                break;
            case R.id.mv_detials_back:
                finish();
                break;
            case R.id.mv_detials_share:


                mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                //是否只有已登录用户才能打开分享选择页
                mController.openShare(SearchMVDetialsActivity.this, false);
                QQShare();
                break;
            default:
                break;
        }
    }


    private void initShare() {

        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void QQShare() {
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享title
        qqShareContent.setTitle(StringResouce.SHARE_TITLE);
        //设置点击分享内容的跳转连接
        qqShareContent.setTargetUrl(shareUrl);

        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享内容的标题
        qzone.setTitle(StringResouce.SHARE_TITLE);
        //设置点击消息的跳转URL
        qzone.setTargetUrl(shareUrl);
        mController.setShareMedia(qzone);

        SinaShareContent shareContent =  new SinaShareContent();
        shareContent.setTitle(StringResouce.SHARE_TITLE);
        shareContent.setShareContent(StringResouce.SHARE_CONTENT + shareUrl);
        mController.setShareMedia(shareContent);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position != 0) {
            newMVUrlId = mvDetialsListViewAdapter.getDataEntities().get(position - 1).getId();
            newUrl = URL.MV_DETIALS_STARTURL + newMVUrlId + URL.MV_DETIALS_ENDURL;
            newDescUrl = URL.MV_DETAILS_HEAD_START + newMVUrlId + URL.MV_DETAILS_HEAD_end;
            initNewData();
            initNewDescData();
        }
    }

    private void initNewData() {
        StringRequest request = new StringRequest(newUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                MVDetials mvDetials = gson.fromJson(response, MVDetials.class);
                newDatas = mvDetials.getData();
//                mvDetialsListViewAdapter = new MVDetialsListViewAdapter(SearchMVDetialsActivity.this, newDatas);
//                mvDetialsListview.setAdapter(mvDetialsListViewAdapter);
                mvDetialsListViewAdapter.refreshData(newDatas);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    private void initNewDescData() {
        StringRequest request = new StringRequest(newDescUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                MVDetialsHead mvDetialsHead = gson.fromJson(response, MVDetialsHead.class);
                newDataEntity = mvDetialsHead.getData();
                mvDetials_singerName.setText(newDataEntity.getSingerName());
                mvDetials_songName.setText(newDataEntity.getVideoName());
                mvDetialsPlayCount.setText(newDataEntity.getPickCount() + "");
                mvDetialsCommentCount.setText(newDataEntity.getBulletCount() + "");
                if (!dataEntity.getDesc().isEmpty()) {
                    mvDetialsDesc.setText(newDataEntity.getDesc());
                } else {
                    mvDetialsDesc.setVisibility(View.GONE);
                }
                newMVPlayUrl = newDataEntity.getMvList().get(0).getUrl();

                initNewMVPlay();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    private void initNewMVPlay() {
        myMediaPlayer.setUrl(newMVPlayUrl);
        mv_detials_seekBar.setMax(myMediaPlayer.getMax());
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mv_detials_seekBar.setProgress(msg.arg1);
                        mv_currentTime.setText(toTime(msg.arg1));
                        break;
                    case 2:
                        mv_rl_control.setVisibility(View.GONE);
                        break;
                }
                return false;
            }
        });
        myMediaPlayer.setHandler(handler);
    }


    public String toTime(int time) {

        time /= 1000;
        int minute = time / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

}
